package com.biwano.swapmyjob.dao;

import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.codec.digest.DigestUtils;

import com.biwano.swapmyjob.objects.Link;


@Stateless
public class LinkDao {
	
	public enum LinkType
	{
		validateEmail;
	}
	
	@PersistenceContext
	EntityManager em;

	public static final Long LinkValidityPeriod = (long) (60 * 60); 
   
	public Link getLink(String id) throws Exception
    {
		Link a = em.find(Link.class, id);
    	return a;
    }
    public String createLink(String login, LinkType action)
    {
		Long creationDate=new Date().getTime();
		Long expirationDate=creationDate + LinkValidityPeriod;
		String tohash = login + action + creationDate.toString() + expirationDate.toString();
		String linkId = DigestUtils.md5Hex(tohash);
		
		Link l = new Link(
				linkId, login, action.name(), creationDate, expirationDate
				);
        em.persist(l);
        
		return linkId;
	}

}
